package com.woniuxy.portal.interceptor;

import com.woniuxy.portal.common.enumeration.Assert;
import com.woniuxy.portal.common.enumeration.BusinessCode;
import com.woniuxy.portal.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yellow Docter
 * @date 2024-10-25
 * @desc 蜗牛创想：www.woniuxy.com
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        log.info("放行OPTIONS 请求:{}",method);

        //判断是否是options请求，如果是则直接放行 OPTIONS  发送请求的预检查
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        //false 拦截 (不会访问到controller)
        //1、拦截 校验token                   authorization
        String token = request.getHeader("authorization");
        //token 不能为null
        Assert.error(!StringUtils.hasText(token), BusinessCode.TOKEN_NOT_EXISTS);
        //token失效
        Assert.error(!jwtUtil.validateToken(token), BusinessCode.INVALID_TOKEN);

        //放行
        return true ;
    }
}
